package com.ZeroCarbon.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ZeroCarbon.domain.po.UserFavorite;
import com.ZeroCarbon.exception.BusinessLogicException;
import com.ZeroCarbon.mapper.UserFavoriteMapper;
import com.ZeroCarbon.service.IUserFavoriteService;
import com.ZeroCarbon.utils.UserHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static com.ZeroCarbon.exception.BusinessLogicException.ERROR_EXCEPTION;

@Service
public class UserFavoriteImplService extends ServiceImpl<UserFavoriteMapper, UserFavorite> implements IUserFavoriteService {

    /**
     * 收藏
     *
     * @param id 记录id
     */
    @Override
    public void collectPost(String id) throws BusinessLogicException {
        //获取用户id
        String userId = UserHolder.getUser();
        //创建收藏类对象
        UserFavorite userFavorite = new UserFavorite(userId, id);
        //保存用户收藏类
        if (!save(userFavorite)) {
            throw new BusinessLogicException(ERROR_EXCEPTION);
        }
    }

    /**
     * 取消收藏
     */
    @Override
    public void unCollect(String id) throws BusinessLogicException {
        //获取用户id
        String userId = UserHolder.getUser();
        //收藏记录查询条件
        LambdaQueryWrapper<UserFavorite> favoriteWrapper = new LambdaQueryWrapper<UserFavorite>()
                .eq(UserFavorite::getId, userId)
                .eq(UserFavorite::getRecordId, id);
        try {
            //从数据库删除记录
            if (!remove(favoriteWrapper)) {
                throw new BusinessLogicException();
            }
        } catch (BusinessLogicException e) {
            throw new BusinessLogicException(ERROR_EXCEPTION);
        }
    }

    /**
     * 获取用户收藏
     */
    @Override
    public List<String> collection() throws BusinessLogicException {
        //获取用户id
        String userId = UserHolder.getUser();
        //构建用户收藏查询器
        LambdaQueryWrapper<UserFavorite> userFavoriteWrapper = new LambdaQueryWrapper<UserFavorite>()
                .eq(UserFavorite::getId, userId);
        //收藏记录列表
        List<UserFavorite> favoriteRecordsList;
        try {
            //查找用户收藏
            favoriteRecordsList = list(userFavoriteWrapper);
        } catch (Exception e) {
            throw new BusinessLogicException(ERROR_EXCEPTION);
        }
        //获取recordId集合返回
        return favoriteRecordsList.stream()
                .map(userFavorite -> (String) BeanUtil.getProperty(userFavorite, "recordId"))
                .collect(Collectors.toList());
    }
}
